<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center>
        <template #default>
          <van-image
            round
            class="avatar"
            :src="profile.photo"
            @click="$refs.iptFile.click()"
          />
          <input
            v-show="false"
            type="file"
            ref="iptFile"
            accept="image/*"
            @change="onFileChange"
          />
        </template>
      </van-cell>
      <van-cell
        title="名称"
        is-link
        :value="profile.name"
        @click="showNameDialogFn"
      />
      <!-- 修改用户名称的对话框 -->
      <van-dialog
        v-model="isShowNameDialog"
        title="修改名称"
        show-cancel-button
        :before-close="onNameDialogBeforeClose"
      >
        <!-- 输入框 -->
        <van-field
          v-model.trim="userName"
          input-align="center"
          maxlength="7"
          placeholder="请输入名称"
          v-focus
        />
      </van-dialog>
      <van-cell title="生日" is-link :value="profile.birthday" @click="showBirthFn()"/>
    </van-cell-group>
    <!-- 修改时间 -->
    <van-popup
      v-model="isShowBirth"
      position="bottom"
      style="height: 50%"
      round
    >
      <!-- 日期选择控件 -->
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择出生日期"
        :min-date="minDate"
        :max-date="maxDate"
        :show-toolbar="true"
        @cancel="isShowBirth=false"
        @confirm="confirmBirthFn"
      />
    </van-popup>
  </div>
</template>

<script>
import { userProfileAPI, updatePhotoAPI, updateProfileAPI } from '@/api'
import { Notify } from 'vant'
import dayjs from 'dayjs'
export default {
  name: 'UserEdit',
  data () {
    return {
      profile: {}, // 用户基本资料
      isShowNameDialog: false,
      userName: '', // 编辑用户名
      isShowBirth: false, // 显示时间选择器
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(),
      currentDate: new Date() // 当前日期
    }
  },
  async created () {
    const res = await userProfileAPI()
    console.log(res)
    this.profile = res.data.data
  },
  methods: {
    async onFileChange (ev) {
      console.log(ev.target.files[0])
      if (ev.target.files.length === 0) return // 防止用户未选择图片
      const pd = new FormData()
      pd.append('photo', ev.target.files[0])
      const res = await updatePhotoAPI(pd)
      console.log(res)
      this.profile.photo = res.data.data.photo
    },
    // 点击名字-出现弹出框
    showNameDialogFn () {
      this.isShowNameDialog = true
      this.userName = this.profile.name // 设置默认显示内容
    },
    // 姓名修改弹出层-关闭前方法
    async onNameDialogBeforeClose (action, done) {
      console.log(action)
      if (action === 'confirm') {
        if (/^[A-Za-z0-9\u4e00-\u9fa5]{1,7}$/.test(this.userName)) {
          // 通过校验，关闭弹窗
          // 调用接口
          const res = await updateProfileAPI({
            userName: this.userName
          })
          // 更新显示更改的名字
          this.profile.name = this.userName
          console.log(res)
          done()
        } else {
          // 没有通过，出现提示
          Notify({
            type: 'warning',
            message: '请输入正确的用户名中英文和数字1-7位'
          })
        }
      } else {
        done()
      }
    },
    // 弹出时间选择框
    showBirthFn () {
      this.isShowBirth = true
      // 回显当前日期
      this.currentDate = new Date(this.profile.birthday)
    },
    // 生日选择
    async confirmBirthFn () {
      console.log(dayjs(this.currentDate).format('YYYY-MM-DD'))
      const dateStr = dayjs(this.currentDate).format('YYYY-MM-DD')
      await updateProfileAPI({
        birthday: dateStr
      })
      // 页面端同步
      this.profile.birthday = dateStr
      // 时间选择器关闭
      this.isShowBirth = false
    }
  }
}
</script>

<style lang="less" scoped>
.user-edit-container {
  text-align: left;
  padding-top: 46px;
  .avatar {
    width: 50px;
    height: 50px;
  }
}
</style>
